//
//  PracticeViewController.m
//  MagicCardDemo
//
//  Created by 向恒 on 15/7/5.
//  Copyright (c) 2015年 向恒. All rights reserved.
//

#import "PracticeViewController.h"
#import "AppDelegate.h"

#import "CardSerialize.h"

#import "CardMap.h"

#import "UploadFileList.h"

@interface PracticeViewController ()

@end

@implementation PracticeViewController
@synthesize queue;
@synthesize btnCard;
@synthesize Schedule;
//@synthesize btnTips;
@synthesize btnFinish;
@synthesize labelTimer;
@synthesize PractiseState = _PractiseState;  //需要一个setter方法，方法在状态为prcready的时候洗牌。这行不注释掉，下面的set方法不起作用
int nClickCnt = 0;
typedef enum
{
    prcready = 1,
    prcing,
    prcpause,
    prcfinsh
}PrcStat;

int timeTick = 0;
NSTimer * timer;

CardMap* queryMap;

AppDelegate* appDelegate;

//-(id)init//不执行，啥意思
//{
//    return self;
//}

-(void) setPractiseState:(NSUInteger)PractiseState
{
    if(PractiseState == prcready && self.PractiseState != prcready)
    {
        //洗牌操作
        queue = [[CardQueue alloc]init];
        [queue ShuffleCards];
        
        timeTick = 0;
    }
    _PractiseState = PractiseState;
    
}


//下一张卡牌
- (IBAction)BtnNextCardClicked:(id)sender {

    
    if(nClickCnt == 0)
    {
        [btnFinish setEnabled:YES];
        self.PractiseState = prcing;  //能不能不实用self就调用setter？
        [self updatePrcStat];
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeMethod) userInfo:nil repeats:YES];
    }
    
    else if(nClickCnt>0)
    {
        
        self.PractiseState = prcing;  //能不能不实用self就调用setter？
        [self updatePrcStat];
        [timer setFireDate:[NSDate date]];
    }
    
    if(nClickCnt<queue.arrCards.count)
    {
        NSString *strCardTip = [NSString stringWithFormat:@"%@",[queue.arrCards objectAtIndex:nClickCnt]];
        //NSString *strCardTip  [queue.arrCards objectAtIndex:nClickCnt];
        [btnCard setTitle:strCardTip forState:UIControlStateNormal];
        nClickCnt++;
        
        //显示第一次练习的进度
        NSString* strSchedule = [NSString stringWithFormat:@"进度：%d/%d",nClickCnt,queue.arrCards.count];
        [Schedule setText:strSchedule];
    }
    else
    {
        
        NSString *strCardTip = @"结束";
        [btnCard setTitle:strCardTip forState:UIControlStateNormal];
        //btnCard.titleLabel.text = strCardTip;
    }

}


//结束训练
- (IBAction)BtnFinishTrainClicked:(id)sender {
    
    self.PractiseState = prcfinsh;
    [self updatePrcStat];
    
    appDelegate = [UIApplication sharedApplication].delegate;
    
    //记录训练结束时间
    NSDate* curDate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString* locationString = [dateFormatter stringFromDate:curDate];
    appDelegate.cardData.TrainQueue.date = locationString;
    
    NSMutableArray * mArr = [[NSMutableArray alloc]initWithObjects: nil];
    
    for(int i = 0;i < nClickCnt;i++)
    {
        [mArr addObject:[queue.arrCards objectAtIndex:i]];
    }

    //保存训练数据到归档类中
    [appDelegate.cardData.Heap.arrCards addObjectsFromArray:queue.arrCards];
    [appDelegate.cardData.TrainQueue.arrCards addObjectsFromArray:mArr];
    appDelegate.cardData.TrainQueue.nCostTime = timeTick;//add 20160123
    //数据归档,在这个地方写文件
    //CardData * cd=  [[CardData alloc]init];
    NSDateFormatter* fileFormatter = [[NSDateFormatter alloc]init];
    [fileFormatter setDateFormat:@"yyyyMMdd--HHmmss"];
    NSString* storedFileName = [fileFormatter stringFromDate:curDate];
    storedFileName  = [storedFileName stringByAppendingString:@".archive"];
    [CardData WriteData:appDelegate.cardData.TrainQueue toFile:storedFileName];
    
    UploadFileList* ufl = [[UploadFileList alloc]init];
    [ufl Add:storedFileName];
    
    //这里清空数据
    [appDelegate.cardData ClearData];
    //需要重新洗牌
    
    [timer invalidate];
    
    //更新签到信息，如果今天已经钱到了，那么久什么都不做。
    //SignInDate
    
    //返回上一级
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    queryMap = [[CardMap alloc]init];
    
    //button点击事件
    [btnCard addTarget:self action:@selector(btnShort:) forControlEvents:UIControlEventTouchUpInside];
    //button长按事件
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 0.8; //定义按的时间
    [btnCard addGestureRecognizer:longPress];

    self.PractiseState = prcready;
    
    [btnFinish setEnabled:false];
}

//短按的话，就提示这个数字对应的意思
-(void)btnShort:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {

        BOOL (^isPureInt)(NSString* string) =
        ^(NSString* string)
        {
            NSScanner* scan = [NSScanner scannerWithString:string];
            int val;
            return (BOOL)([scan scanInt:&val] && [scan isAtEnd]);
        };
        
        //判断按钮的文本是不是数字，如果是数字，那么查询出这个数字对应的意思
        BOOL bRst = isPureInt(btnCard.titleLabel.text);
        if(bRst)
        {
            for(int i = 0;i < [queryMap.books count];i++)
            {
                NSString* query = [queryMap.books objectAtIndex:i];
                if([query isEqualToString:btnCard.titleLabel.text])
                {
                    NSString* result = [queryMap.details objectAtIndex:i];
                    //[btnCard.titleLabel setText:result];
                    [btnCard setTitle:result forState:UIControlStateNormal];
                    break;
                }
                
            }
        }
        //如果不是数字，那么将将当前的数字现实出来，这个数字存在哪里了？queue.arrCards
        else
        {
            
        }
        
    }
}

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        //NSLog(@"长按事件");
        //UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"消息" message:@"确定删除该模式吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
        //[alert show];
        switch(self.PractiseState)
        {
            case prcing:
                [btnCard setTitle:@"暂停" forState:UIControlStateNormal];
                self.PractiseState = prcpause;
                [timer setFireDate:[NSDate distantFuture]];
                break;
            case prcpause:
            {
                NSString *strCardTip = [NSString stringWithFormat:@"%@",[queue.arrCards objectAtIndex:nClickCnt-1]];
                //NSString *strCardTip  [queue.arrCards objectAtIndex:nClickCnt];
                [btnCard setTitle:strCardTip forState:UIControlStateNormal];
                self.PractiseState = prcing;
                [timer setFireDate:[NSDate date]];
            }
                break;
                
            default:
                break;
        }
    }
}

-(void)updatePrcStat
{
    //更新状态
    switch (self.PractiseState) {
        case prcready:
            [self.labelPrcStat setText:@"状态：准备"];
            break;
        case prcing:
            [self.labelPrcStat setText:@"状态：进行中"];
            break;
        case prcpause:
            [self.labelPrcStat setText:@"状态：暂停"];
            break;
        case prcfinsh:
            [self.labelPrcStat setText:@"状态：结束"];
            break;
        default:
            break;
    }
}

-(void)timeMethod
{
    timeTick++;
    
    //更新计时
    NSString*(^CalcTimeWithSeconds)(int) = ^(int num)
    {
        int hour,min,sec;
        sec = num%60;  //剩下的秒数
        min = num/60;  //总分钟数
        hour = min/60;  //总小时数
        min = min%60;  //计算了总小时数之后剩下的分钟数
        NSString * strTime = [NSString stringWithFormat:@"时间：%02d:%02d:%02d",hour,min,sec];
        //[strTime description];
        NSLog(strTime);
        return strTime;
    };
    
    [labelTimer setText:CalcTimeWithSeconds(timeTick)];
}

//长按响应的事件

-(IBAction)handleLongPress:(id)sender{
    
    UIButton *button=(UIButton*)[(UILongPressGestureRecognizer *)sender view];
    
    switch(self.PractiseState)
    {
        case prcing:
            [button setTitle:@"暂停" forState:UIControlStateNormal];
            self.PractiseState = prcpause;
            break;
        case prcpause:
        {
            NSString *strCardTip = [NSString stringWithFormat:@"%@",[queue.arrCards objectAtIndex:nClickCnt-1]];
            //NSString *strCardTip  [queue.arrCards objectAtIndex:nClickCnt];
            [btnCard setTitle:strCardTip forState:UIControlStateNormal];
            self.PractiseState = prcing;
        }
            break;

            default:
            break;
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    nClickCnt = 0;//为洗牌服务，BtnNextCardClicked一开始就要判断这个值的
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
